{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "6377cd98",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(468, 448, 3)\n",
      "(468, 448)\n",
      "(32, 24)\n"
     ]
    }
   ],
   "source": [
    "import cv2 as cv\n",
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "#读取模板和待寻找目标的图像\n",
    "img_rgb = cv.imread('../data/mario.png')\n",
    "img_org = img_rgb.copy()\n",
    "print(img_rgb.shape)\n",
    "img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)\n",
    "print(img_gray.shape)\n",
    "template = cv.imread('../data/mario_coin.png',0)\n",
    "print(template.shape)\n",
    "w, h = template.shape[::-1]\n",
    "\n",
    "\n",
    "#将模板和图像进行匹配得到每个像素的相似度\n",
    "res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)\n",
    "\n",
    "#筛选满足设定相似度阈值的像素位置\n",
    "threshold = 0.9\n",
    "loc = np.where( res >= threshold)    \n",
    "#表示比较res每个元素和阈值threshold，如果为真，则y添加至第一维数组，x添加至第二维数组\n",
    "\n",
    "#标记结果在原图\n",
    "# cordXs,cordYs = loc[1],loc[0]\n",
    "# for idx,X in enumerate(cordXs):\n",
    "#     cv.rectangle(img_rgb, (X,cordYs[idx]), (X + w, cordYs[idx] + h), \n",
    "#                  (0,0,255), 1)\n",
    "cord = []\n",
    "for y in range(res.shape[0]):\n",
    "    for x in range(res.shape[1]):\n",
    "        if res[y][x] > threshold:\n",
    "            cord.append((x,y))\n",
    "            \n",
    "for (X,Y) in cord:\n",
    "    cv.rectangle(img_rgb,(X,Y),(X + w, Y + h),(0,0,255),1)\n",
    "\n",
    "cv.imshow(\"res\", res)\n",
    "cv.imshow(\"img_org\", img_org)\n",
    "cv.imshow(\"img_rgb\", img_rgb)\n",
    "cv.waitKey(0)\n",
    "cv.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "838f6361",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
